import re
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from appAdminUseclassroom.models import ClassroomuseinfoIf, Classroombasicinfo, Reserve, User

# from models import Reserve
#
from .models import ClassroomuseinfoJingguan, ClassroomuseinfoJidian, ClassroomuseinfoWaiyu

num_entry = 50
ListAll = []  # 遍历数据库得到的数据
data = []  # 传送到前端的数据
list = ClassroomuseinfoIf.objects.all()
list1 = Classroombasicinfo.objects.all()
for classInDatabase in list:  # 遍历数据库中的教室表，
    responseDate = {}
    responseDate['use_id'] = classInDatabase.use_id
    responseDate['cid'] = classInDatabase.cid
    responseDate['name'] = str(responseDate['cid'] // 5 + 1) + '0' + str(responseDate['cid'] % 5)
    responseDate['week'] = classInDatabase.week
    responseDate['day'] = classInDatabase.day
    responseDate['time'] = classInDatabase.time
    responseDate['state'] = classInDatabase.state
    if classInDatabase.cid <= 20:
        responseDate['attribute'] = '阶梯教室'
    else:
        responseDate['attribute'] = '实验室'
    # responseDate['attribute'] = Classroombasicinfo.objects.filter(cid=classInDatabase.cid)[0].attribute
    responseDate['remark'] = classInDatabase.remark
    ListAll.append(responseDate)


# 展示设备管理页面
def useInfo_list(request):
    return render(request, 'admin_useClassroom.html')


def judgeNone(s):
    if s != None:
        return int(s)
    else:
        return 0


# 获取设备列表数据
def admin_useInfo(request):
    formDataInt = {}
    formDataInt['floor'] = judgeNone(request.POST.get('floor'))
    formDataInt['room'] = judgeNone(request.POST.get('room'))
    formDataInt['week'] = judgeNone(request.POST.get('week'))
    formDataInt['day'] = judgeNone(request.POST.get('day'))
    formDataInt['time'] = judgeNone(request.POST.get('time'))
    formDataInt['state'] = judgeNone(request.POST.get('state'))

    # 给每个条件都建立一个表,遍历listall,符合条件就append listall中的下标
    list_floor = []
    list_room = []
    list_week = []
    list_day = []
    list_time = []
    list_state = []

    i = 0
    for classroom in ListAll:
        # 没有选择这个选项，就把所有的情况都算上
        if classroom['cid'] // 5 + 1 == formDataInt['floor'] or formDataInt['floor'] == 0:
            list_floor.append(i)
        if classroom['cid'] % 5 == formDataInt['room'] or formDataInt['room'] == 0:
            list_room.append(i)
        if formDataInt['week'] == classroom['week'] or formDataInt['week'] == 0:
            list_week.append(i)
        if formDataInt['day'] == classroom['day'] or formDataInt['day'] == 0:
            list_day.append(i)
        if formDataInt['time'] == classroom['time'] or formDataInt['time'] == 0:
            list_time.append(i)
        if formDataInt['state'] == classroom['state'] or formDataInt['state'] == 0:
            list_state.append(i)
        i += 1

    # 找出六个列表的交集
    list_search = set(list_floor) & set(list_room) \
                  & set(list_week) & set(list_day) & set(list_day) \
                  & set(list_time) & set(list_state)
    if not list_search:
        pass
    elif list_search:
        data.clear()  # 每次查询都清空上次查询的表格
        for i in list_search:
            data.append(ListAll[i])
    return render(request, "admin_useClassroom.html", {'List': data[0:num_entry]})


# 编辑设备
def update_useInfo(request):
    # 从前端获取数据
    update_id = int(request.POST.get('update_id'))
    data_id = int(request.POST.get('data_id'))  # 向前端传递数据的数组index，为了加快速度，只有在每次重新查询的时候，才会从数据库load所有数据
    update_select = int(request.POST.get('update_select'))
    update_remark = request.POST.get('update_remark')

    # 修改数据库中的内容
    ClassroomuseinfoIf.objects.filter(use_id=update_id).update(state=update_select)
    ClassroomuseinfoIf.objects.filter(use_id=update_id).update(remark=update_remark)
    # 修改传给前端的值
    # print(data[data_id]['state'],data[data_id]['remark'])
    data[data_id]['state'] = update_select
    data[data_id]['remark'] = update_remark

    return render(request, "admin_useClassroom.html", {'List': data[0:num_entry]})


def transday(text):
    if text == 1:
        text = "星期一"
    if text == 2:
        text = "星期二"
    if text == 3:
        text = "星期三"
    if text == 4:
        text = "星期四"
    if text == 5:
        text = "星期五"
    if text == 6:
        text = "星期六"
    if text == 7:
        text = "星期日"
    return text


def transweek(text):
    if text == 1:
        text = "第一周"
    if text == 2:
        text = "第二周"
    if text == 3:
        text = "第三周"
    if text == 4:
        text = "第四周"
    if text == 5:
        text = "第五周"
    if text == 6:
        text = "第六周"
    if text == 7:
        text = "第七周"
    if text == 8:
        text = "第八周"
    if text == 9:
        text = "第九周"
    return text


def transtime(text):
    if text == 1:
        text = "第一节"
    if text == 2:
        text = "第二节"
    if text == 3:
        text = "第三节"
    if text == 4:
        text = "第四节"
    if text == 5:
        text = "第五节"
    if text == 6:
        text = "第六节"
    if text == 7:
        text = "第七节"
    if text == 8:
        text = "第八节"
    return text


def transhenfen(text):
    if text == 1:
        text = "老师"
    if text == 2:
        text = "学生"
    return text


class StuReserve(View):

    def get(slef, request):
        data = request.GET
        uid = request.session['uid'] if 'uid' in request.session else 4
        cc = ""
        try:
            if "floor" in data:
                floor = data.get("floor")
                room = data.get("room")
                cc = ClassroomuseinfoIf.objects.all()
                if floor != "0" and room != "0":
                    roomname = str(floor) + "0" + str(room)
                    classroominfo = Classroombasicinfo.objects.filter(classroom_name=int(roomname))
                    cc = cc.filter(cid=classroominfo[0].cid)
                elif floor != "0" and room == "0":
                    ll = []
                    for i in range(1, 6):
                        classroominfo = Classroombasicinfo.objects.filter(classroom_name=int(f"{floor}" + "0" + str(i)))
                        ll.append(int(classroominfo[0].cid))
                    cc = cc.filter(cid__in=ll)
                elif floor == "0" and room != "0":
                    ll = []
                    for i in range(1, 6):
                        classroominfo = Classroombasicinfo.objects.filter(classroom_name=int(f"{i}" + "0" + str(room)))
                        ll.append(classroominfo[0].cid)
                    cc = cc.filter(cid__in=ll)
                week = data.get("week")
                if week != "0":
                    cc = cc.filter(week=week)
                day = data.get("day")
                if day != "0":
                    cc = cc.filter(day=day)
                time = data.get("time")
                if time != "0":
                    cc = cc.filter(time=time)
                state = data.get("state")
                if state != "0":
                    cc = cc.filter(state=state)
            else:
                pass
            # Classroombasicinfo.objects.all()
            # classroominfo = Classroombasicinfo.objects.filter(classroom_name = int(roomname))
        except:
            pass
        reserves = Reserve.objects.filter(user_id=uid)
        id2name = {1: '逸夫楼', 2:'机电楼', 3:'经管楼', 4:'外语楼'}
        for reserve in reserves:
            ccc = Classroombasicinfo.objects.filter(cid=reserve.classroom_id)
            reserve.classroom_id = ccc[0].classroom_name
            reserve.time = transtime(reserve.time)
            reserve.building_name = id2name[reserve.building_id]
            reserve.week = transweek(reserve.week)
            reserve.day = transday(reserve.day)
            reserve.time = reserve.week + reserve.day + reserve.time
            if reserve.state == 0:
                reserve.state = "待审核"
            elif reserve.state == 1:
                reserve.state = "已审核"
            else:
                reserve.state = "已驳回"
            reserve.recall_remark = reserve.remark.split('&=&')[1] if len(reserve.remark.split('&=&')) > 1 else ''
            reserve.remark = reserve.remark.split('&=&')[0]
        # if cc:
        #     classroomuserinfos = cc
        #     # classroomuserinfos = Classroomuseinfo.objects.filter(
        #     #     week=week, day=day, time=time, state=state, cid=classroominfo[0].cid)
        #     # print(classroomuserinfos[0].items())
        #     for classroomuserinfo in classroomuserinfos:
        #         if classroomuserinfo.state == 1:
        #             reserver = Reserve.objects.filter(week=classroomuserinfo.week, day=classroomuserinfo.day,
        #                                               time=classroomuserinfo.time, classroom_id=classroomuserinfo.cid,
        #                                               user_id=uid)
        #             # if reserver and reserver[-1].state !=  2:
        #             if reserver:
        #                 classroomuserinfo.state = "已预约"
        #             else:
        #                 classroomuserinfo.state = "空闲"
        #         else:
        #             classroomuserinfo.state = "已预约"
        #         cc = Classroombasicinfo.objects.filter(cid=classroomuserinfo.cid)
        #         classroomuserinfo.cid = cc[0].classroom_name
        #         classroomuserinfo.day = transday(classroomuserinfo.day)
        #         classroomuserinfo.time = transtime(classroomuserinfo.time)
        #         classroomuserinfo.week = transweek(classroomuserinfo.week)
        return render(request, "stu_reserve.html", locals())

    def post(self, request):
        data = request.POST
        datatype = data.get("datatype")
        if datatype == "update":
            # 表示再次申请
            rer = Reserve.objects.filter(reserve_id=data.get("id"))[0]
            rer.state = 0
            rer.save()
        elif datatype == "delete":
            # 撤销申请
            r = Reserve.objects.filter(reserve_id=data.get("id"))[0]
            buildings = [ClassroomuseinfoIf, ClassroomuseinfoJidian, ClassroomuseinfoJingguan, ClassroomuseinfoWaiyu]
            # 释放教室排版信息
            print(r.state)
            if r.state == 1:
                buildings[r.building_id-1].objects.filter(cid=r.classroom_id, week=r.week, time=r.time, day=r.day).update(state=1)
            Reserve.objects.filter(reserve_id=data.get("id")).delete()
        else:
            c = Classroombasicinfo.objects.filter(cid=int(data.get("cid")))
            remark = data.get("remark")
            uid = request.session['uid']
            user = User.objects.filter(uid=request.session['uid'])[0]
            filtered = Reserve.objects.filter(classroom_id=int(data.get("cid")),week=data.get("week"), day=data.get("day"), time=data.get("time"), user_id=uid)
            if len(filtered) > 0:
                r = filtered[0]
                r.remark = remark
                r.state = 0
                r.save()
            else:
                r = Reserve.objects.create(
                    classroom_id=c[0].cid, user_id=user.uid, state=0, time=data.get("time"), building_id=c[0].building_id,
                    week=data.get("week"), day=data.get("day"), remark=remark)
            s = {}
            id2name = {1: '逸夫楼', 2: '机电楼', 3: '经管楼', 4: '外语楼'}
            s['classroom'] = Classroombasicinfo.objects.filter(cid=r.classroom_id)[0].classroom_name
            s['building_name'] = id2name[r.building_id]
            s['time'] = transweek(int(r.week)) + transday(int(r.day)) + transtime(int(r.time))
            s['state'] = "待审核"
            s['id'] = r.reserve_id
            s['remark'] = remark
            s['recall_remark'] = ''
            return JsonResponse({"msg": "ok", 'data': s})
        return JsonResponse({"msg": "ok"})


def filters():
    pass


class TeaReserve(View):

    def get(slef, request):

        data = request.GET
        uid = request.session['uid'] if 'uid' in request.session else 4
        cc = ""
        try:
            if "floor" in data:
                floor = data.get("floor")
                room = data.get("room")
                cc = ClassroomuseinfoIf.objects.all()
                if floor != "0" and room != "0":
                    roomname = str(floor) + "0" + str(room)
                    classroominfo = Classroombasicinfo.objects.filter(classroom_name=int(roomname))
                    cc = cc.filter(cid=classroominfo[0].cid)
                elif floor != "0" and room == "0":
                    ll = []
                    for i in range(1, 6):
                        classroominfo = Classroombasicinfo.objects.filter(classroom_name=int(f"{floor}" + "0" + str(i)))
                        ll.append(int(classroominfo[0].cid))
                    cc = cc.filter(cid__in=ll)
                elif floor == "0" and room != "0":
                    ll = []
                    for i in range(1, 6):
                        classroominfo = Classroombasicinfo.objects.filter(classroom_name=int(f"{i}" + "0" + str(room)))
                        ll.append(classroominfo[0].cid)
                    cc = cc.filter(cid__in=ll)
                week = data.get("week")
                if week != "0":
                    cc = cc.filter(week=week)
                day = data.get("day")
                if day != "0":
                    cc = cc.filter(day=day)
                time = data.get("time")
                if time != "0":
                    cc = cc.filter(time=time)
                state = data.get("state")
                if state != "0":
                    cc = cc.filter(state=state)
            else:
                pass
            # Classroombasicinfo.objects.all()
            # classroominfo = Classroombasicinfo.objects.filter(classroom_name = int(roomname))
        except:
            pass
        reserves = Reserve.objects.filter(user_id=uid)
        id2name = {1: '逸夫楼', 2:'机电楼', 3:'经管楼', 4:'外语楼'}
        for reserve in reserves:
            ccc = Classroombasicinfo.objects.filter(cid=reserve.classroom_id)
            reserve.classroom_id = ccc[0].classroom_name
            reserve.time = transtime(reserve.time)
            reserve.building_name = id2name[reserve.building_id]
            reserve.week = transweek(reserve.week)
            reserve.day = transday(reserve.day)
            reserve.time = reserve.week + reserve.day + reserve.time
            if reserve.state == 0:
                reserve.state = "待审核"
            elif reserve.state == 1:
                reserve.state = "已审核"
            else:
                reserve.state = "已驳回"
            reserve.recall_remark = reserve.remark.split('&=&')[1] if len(reserve.remark.split('&=&')) > 1 else ''
            reserve.remark = reserve.remark.split('&=&')[0]
        return render(request, "teacher_reserve.html", locals())

    def post(self, request):
        data = request.POST
        datatype = data.get("datatype")
        if datatype == "update":
            # 表示再次申请
            rer = Reserve.objects.filter(reserve_id=data.get("id"))[0]
            rer.state = 0
            rer.save()
        elif datatype == "delete":
            # 撤销申请
            r = Reserve.objects.filter(reserve_id=data.get("id"))[0]
            buildings = [ClassroomuseinfoIf, ClassroomuseinfoJidian, ClassroomuseinfoJingguan, ClassroomuseinfoWaiyu]

            # 释放教室排版信息
            if r.state == 1:
                buildings[r.building_id-1].objects.filter(cid=r.classroom_id, week=r.week, time=r.time, day=r.day).update(state=1)
            Reserve.objects.filter(reserve_id=data.get("id")).delete()
        else:
            c = Classroombasicinfo.objects.filter(cid=int(data.get("cid")))
            remark = data.get("remark")
            uid = request.session['uid']
            user = User.objects.filter(uid=request.session['uid'])[0]
            filtered = Reserve.objects.filter(classroom_id=int(data.get("cid")),week=data.get("week"), day=data.get("day"), time=data.get("time"), user_id=uid)
            if len(filtered) > 0:
                r = filtered[0]
                r.remark = remark
                r.state = 0
                r.save()
            else:
                r = Reserve.objects.create(
                    classroom_id=c[0].cid, user_id=user.uid, state=0, time=data.get("time"), building_id=c[0].building_id,
                    week=data.get("week"), day=data.get("day"), remark=remark)
            s = {}
            id2name = {1: '逸夫楼', 2: '机电楼', 3: '经管楼', 4: '外语楼'}
            s['classroom'] = Classroombasicinfo.objects.filter(cid=r.classroom_id)[0].classroom_name
            s['building_name'] = id2name[r.building_id]
            s['time'] = transweek(int(r.week)) + transday(int(r.day)) + transtime(int(r.time))
            s['state'] = "待审核"
            s['id'] = r.reserve_id
            s['remark'] = remark
            s['recall_remark'] = ''
            return JsonResponse({"msg": "ok", 'data': s})
        return JsonResponse({"msg": "ok"})


class AdminReserve(View):

    def get(self, request):
        data = request.GET
        state1 = 0
        state2 = 0
        if "reserve_name" not in data:
            reserves = Reserve.objects.all()
            state2 = len(reserves)
            list1 = []
            for reserve in reserves:
                dict1 = {}
                user = User.objects.filter(uid=reserve.user_id)
                dict1["shenfen"] = transhenfen(user[0].state)
                dict1["name"] = user[0].name
                try:
                    classroom = Classroombasicinfo.objects.filter(cid=reserve.classroom_id)[0]
                except:
                    continue
                reserve.classroom_id = classroom.classroom_name
                reserve.time = transtime(reserve.time)
                reserve.week = transweek(reserve.week)
                reserve.day = transday(reserve.day)
                reserve.time = reserve.week + reserve.day + reserve.time
                dict1["time"] = reserve.time
                if reserve.state == 0:
                    reserve.state = "待审核"
                    state1 = state1 + 1
                elif reserve.state == 1:
                    reserve.state = "已审核"
                else:
                    reserve.state = "已驳回"
                dict1["remark"] = reserve.remark.split("&=&")[0]
                dict1["state"] = reserve.state
                dict1["reserve_id"] = reserve.reserve_id
                dict1["classroom_id"] = reserve.classroom_id
                list1.append(dict1)
        else:
            name = data.get("reserve_name")
            user = User.objects.filter(name__icontains=name)
            try:
                reserves = Reserve.objects.filter(user_id=user[0].uid)
            except:
                return render(request, "admin_reserve.html", locals())
            state2 = len(reserves)
            list1 = []
            for reserve in reserves:
                dict1 = {}
                dict1["name"] = user[0].name
                dict1["shenfen"] = transhenfen(user[0].state)
                try:
                    classroom = Classroombasicinfo.objects.filter(cid=reserve.classroom_id)[0]
                except:
                    continue
                reserve.classroom_id = classroom.classroom_name
                reserve.time = transtime(reserve.time)
                reserve.week = transweek(reserve.week)
                reserve.day = transday(reserve.day)
                reserve.time = reserve.week + reserve.day + reserve.time
                dict1["time"] = reserve.time
                if reserve.state == 0:
                    reserve.state = "待审核"
                    state1 = state1 + 1
                elif reserve.state == 1:
                    reserve.state = "已审批"
                else:
                    reserve.state = "已驳回"
                dict1["state"] = reserve.state
                dict1["reserve_id"] = reserve.reserve_id
                dict1["classroom_id"] = reserve.classroom_id
                list1.append(dict1)
        return render(request, "admin_reserve.html", locals())

    def post(self, request):
        data = request.POST
        reserveid = data.get("id")
        remark = data.get("remark")
        state = data.get("state")
        f = Reserve.objects.filter(reserve_id=reserveid)
        if len(f) > 0:
            r = f[0]
            old_remark = r.remark.split("&=&")[0]
            Reserve.objects.filter(reserve_id=reserveid).update(state=state, remark=old_remark+"&=&"+remark)
            buildings = [ClassroomuseinfoIf, ClassroomuseinfoJidian, ClassroomuseinfoJingguan, ClassroomuseinfoWaiyu]
            buildings[r.building_id - 1].objects.filter(cid=r.classroom_id, week=r.week, time=r.time, day=r.day).update(
                    state=1)
        return JsonResponse({"msg": "ok"})


def show_table(request):
    return redirect(reverse("courseSchedule:table") + f"?id={request.session.get('uid')}")